package org.example.backend.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.backend.dto.OrderDTO;
import org.example.backend.dto.OrderExportDTO;
import org.example.backend.entity.Cart;
import org.example.backend.entity.Order;
import org.example.backend.entity.OrderItem;
import org.example.backend.entity.WaterProduct;
import org.example.backend.mapper.OrderItemMapper;
import org.example.backend.mapper.OrderMapper;
import org.example.backend.service.CartService;
import org.example.backend.service.OrderService;
import org.example.backend.service.WaterProductService;
import org.example.backend.util.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private CartService cartService;

    @Autowired
    private WaterProductService waterProductService;

    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private ExcelExportUtil excelExportUtil;

    @Override
    @Transactional
    public Long createOrder(OrderDTO orderDTO) {
        // 生成订单编号
        String orderNo = generateOrderNo();
        
        // 获取购物车列表
        List<Cart> cartList = cartService.listByIds(orderDTO.getCartIds());
        if (cartList.isEmpty()) {
            throw new RuntimeException("购物车为空");
        }
        
        // 验证商品库存
        for (Cart cart : cartList) {
            WaterProduct product = waterProductService.getById(cart.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在");
            }
            if (product.getStatus() == 0) {
                throw new RuntimeException("商品已下架");
            }
            if (product.getStock() < cart.getQuantity()) {
                throw new RuntimeException("商品库存不足");
            }
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(orderDTO.getUserId());
        order.setTotalAmount(orderDTO.getTotalAmount());
        order.setAddress(orderDTO.getAddress());
        order.setPhone(orderDTO.getPhone());
        order.setRemark(orderDTO.getRemark());
        order.setStatus(0); // 待接单
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        
        // 保存订单
        save(order);
        
        // 创建订单明细
        List<OrderItem> orderItems = new ArrayList<>();
        for (Cart cart : cartList) {
            WaterProduct product = waterProductService.getById(cart.getProductId());
            
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getImage());
            orderItem.setPrice(product.getPrice());
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setSubtotal(product.getPrice().multiply(java.math.BigDecimal.valueOf(cart.getQuantity())));
            
            orderItems.add(orderItem);
            
            // 减少库存
            product.setStock(product.getStock() - cart.getQuantity());
            waterProductService.updateById(product);
        }
        
        // 批量保存订单明细（逐个插入）
        for (OrderItem orderItem : orderItems) {
            orderItemMapper.insert(orderItem);
        }
        
        // 删除购物车
        cartService.removeByIds(orderDTO.getCartIds());
        
        return order.getId();
    }

    @Override
    public boolean cancelOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 只有待接单状态的订单可以取消
        if (order.getStatus() != 0) {
            throw new RuntimeException("当前订单状态不允许取消");
        }
        
        // 更新订单状态
        order.setStatus(4); // 已取消
        order.setUpdateTime(new Date());
        
        // 恢复库存
        List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());
        for (OrderItem orderItem : orderItems) {
            WaterProduct product = waterProductService.getById(orderItem.getProductId());
            if (product != null) {
                product.setStock(product.getStock() + orderItem.getQuantity());
                waterProductService.updateById(product);
            }
        }
        
        return updateById(order);
    }

    @Override
    public boolean takeOrder(Long id, Long adminId) {
        Order order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 只有待接单状态的订单可以接单
        if (order.getStatus() != 0) {
            throw new RuntimeException("当前订单状态不允许接单");
        }
        
        // 更新订单状态
        order.setAdminId(adminId);
        order.setStatus(1); // 已接单
        order.setUpdateTime(new Date());
        
        return updateById(order);
    }

    @Override
    public boolean startDelivery(Long id) {
        Order order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 只有已接单状态的订单可以开始配送
        if (order.getStatus() != 1) {
            throw new RuntimeException("当前订单状态不允许开始配送");
        }
        
        // 更新订单状态
        order.setStatus(2); // 配送中
        order.setUpdateTime(new Date());
        
        return updateById(order);
    }

    @Override
    public boolean completeOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 只有配送中状态的订单可以完成
        if (order.getStatus() != 2) {
            throw new RuntimeException("当前订单状态不允许完成");
        }
        
        // 更新订单状态
        order.setStatus(3); // 已完成
        order.setUpdateTime(new Date());
        
        return updateById(order);
    }

    @Override
    public boolean updateOrderStatus(Long id, Integer status) {
        Order order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 检查状态值是否有效
        if (status < 0 || status > 4) {
            throw new RuntimeException("无效的订单状态");
        }
        
        // 更新订单状态
        order.setStatus(status);
        order.setUpdateTime(new Date());
        
        return updateById(order);
    }

    @Override
    @Transactional
    public boolean deleteOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 删除订单项
        orderItemMapper.deleteByOrderId(id);
        
        // 删除订单
        return removeById(id);
    }

    @Override
    public Page<Order> pageOrder(Page<Order> page, String keyword, Integer status, Long userId, Long adminId) {
        return baseMapper.pageOrder(page, keyword, status, userId, adminId);
    }

    @Override
    public Order getOrderDetail(Long id) {
        Order order = baseMapper.selectOrderDetailById(id);
        if (order != null) {
            // 查询订单项
            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(id);
            order.setOrderItems(orderItems);
        }
        return order;
    }
    
    @Override
    public void exportOrder(HttpServletResponse response, String keyword, Integer status, Long userId, Long adminId, 
                         Date startDate, Date endDate) throws IOException {
        // 获取导出数据
        List<OrderExportDTO> exportData = getOrderExportData(keyword, status, userId, adminId, startDate, endDate);
        
        // 导出Excel
        excelExportUtil.export(response, "订单数据", "订单列表", OrderExportDTO.class, exportData);
    }
    
    @Override
    public List<OrderExportDTO> getOrderExportData(String keyword, Integer status, Long userId, Long adminId, 
                                               Date startDate, Date endDate) {
        return baseMapper.selectOrderExportData(keyword, status, userId, adminId, startDate, endDate);
    }

    /**
     * 生成订单编号
     *
     * @return 订单编号
     */
    private String generateOrderNo() {
        // 生成订单编号：当前时间戳 + 4位随机数
        return System.currentTimeMillis() + String.format("%04d", (int) (Math.random() * 10000));
    }
}